<template>
  <div class="login">
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <div class="login-box">
      <!-- 关闭按钮 -->
      <img
        class="close"
        src="@/assets/img/close.png"
        alt=""
        @click="changeIsShowLoginModal(false)"
      />
      <ul class="title">
        <li
          :class="isShowForm == true ? 'active' : ''"
          @click="isShowForm = true"
        >
          手机号码登录
        </li>
        <li style="margin: -2px 10px 0; cursor: auto">|</li>
        <li :class="isShowForm == false ? 'active' : ''" @click="weixinClickFn">
          微信扫码登录
        </li>
      </ul>
      <!-- //登录主体 -->
      <div class="body">
        <!--  表单信息主体 -->
        <div class="form" v-show="isShowForm">
          <!-- 输入手机号 -->
          <div class="input-group">
            <input
              type="text"
              name=""
              id=""
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <!-- 滑块验证码 -->
          <slide-verify
            :l="42"
            :r="20"
            :w="362"
            :h="140"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
            :style="{ width: '100%' }"
            class="slide-box"
            ref="slideBlock"
            :slider-text="msg"
          ></slide-verify>
          <!-- 获取验证码 -->
          <div class="input-group">
            <input
              type="text"
              name=""
              id=""
              placeholder="请输入验证码"
              v-model="SMScode"
            />
            <div class="get-code btn">
              <span v-show="!isShowCount" @click="getSMScode">获取验证码</span>
              <span v-show="isShowCount">{{ count }}s</span>
            </div>
          </div>
          <div class="btn" type="button" @click="submitLogin">登录</div>
        </div>
        <!--  //微信扫码登录 -->
        <div class="qrcode" v-show="!isShowForm" id="weixin">微信扫码登录</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import {
  SendSMSAPI,
  PhoneLoginAPI,
  PhonBindWxAPI,
  userProfilesAPI,
} from "@/request/api";
import { validatePhoneNumber } from "@/utils/index";
export default {
  data() {
    return {
      //是否展示表单
      isShowForm: true,
      //滑块提示信息
      msg: "向右滑动",
      //输入的手机号
      phoneNumber: "",
      //输入的验证码
      SMScode: "",
      //倒计时
      count: 6,
      //是否显示倒计时
      isShowCount: false,
      //倒计时定时器
      timer: null,
    };
  },
  methods: {
    ...mapMutations({
      //修改是否显示登陆模态框
      changeIsShowLoginModal: "showLogin/changeIsShowLoginModal",
      //修改用户是否登陆
      changeIsLogin: "loginStatus/changeIsLogin",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "ToastStatus/asyncChangeIsShowToast",
      asyncChanUserInfo: "userInfo/asyncChanUserInfo",
    }),

    /* 切换微信扫码登录 */
    weixinClickFn() {
      // 点击了微信扫码登录
      this.isShowForm = false;
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwNCi5pbXBvd2VyQm94IC5pbmZvIHsNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0KDQouaW1wb3dlckJveCAucXJjb2RlIHsNCiAgICBtYXJnaW4tdG9wOiAtMTZweDsNCiAgICBtYXJnaW4tbGVmdDogMzhweDsNCiAgICBib3JkZXI6IDBweCBzb2xpZCAjZTJlMmUyOw0KfQ==",
      });
    },

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    //倒计时方法
    countDown() {
      timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          this.count = 60;
          clearInterval(this.timer);
          this.isShowCount = false;
        }
      }, 1000);
    },

    /* 获取验证码按钮 */
    async getSMScode() {
      // 1.调用封装的方法正则校验手机号
      if (!validatePhoneNumber(this.phoneNumber)) {
        /* 调用Vuex 中 asyncChangeIsShowToast给一个对象 */
        this.asyncChangeIsShowToast({
          msg: "请输入正确的手机号",
          type: "warning",
        });
        return;
      }
      //2.验证滑块
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncChangeIsShowToast({
          msg: "滑块验证失败",
          type: "warning",
        });
        return;
      }

      //4.向后端请求验证码
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      console.log("向后端请求验证码-----", res);
      //如果发生验证码失败则不执行后面代码
      if (!res) return;
      //3.显示倒计时并调用倒计时方法
      this.isShowCount = true;
      this.countDown();
    },

    /* 登录按钮 */
    async submitLogin() {
      // 1.调用封装的方法正则校验手机号
      if (!validatePhoneNumber(this.phoneNumber)) {
        /* 调用Vuex 中 asyncChangeIsShowToast给一个对象 */
        this.asyncChangeIsShowToast({
          msg: "请输入正确的手机号",
          type: "warning",
        });
        return;
      }
      //2.验证滑块
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncChangeIsShowToast({
          msg: "滑块验证失败",
          type: "warning",
        });
        return;
      }
      //3.是否输入验证码
      if (!this.SMScode.trim()) {
        this.asyncChangeIsShowToast({
          msg: "请输入手机验证码",
          type: "warning",
        });
        return;
      }
      //调用手机号PhoneLoginAPI方法向后端发生请求

      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //先判断有没有uuid,如果没有则调用手机号绑定微信的接口并将uuid传过去
        res = await PhonBindWxAPI({
          verifyCode: this.SMScode,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        //如果有uuid,则调用正常的手机号登录的接口
        res = await PhoneLoginAPI({
          verifyCode: this.SMScode,
          phone: this.phoneNumber,
        });
      }
      if (!res) return;

      /* 登录成功之后的逻辑 */
      //1.提示登录成功
      this.asyncChangeIsShowToast({
        /* 调用Vuex 中 asyncChangeIsShowToast给一个对象 */
        msg: "登录成功",
        type: "success",
      });
      //2.关闭登录窗口
      this.changeIsShowLoginModal(false);
      //3.保存后端返回token值
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      //4.用户登录状态切换
      this.changeIsLogin(true);
      console.log("手机号登录成功-------", res);
      //5.登录成功后删除uuid和地址栏的code
      this.$router.push(this.$route.path);
      if (uuid) {
        localStorage.removeItem("uuid");
      }
      //6.调用方法向后端发起请求获取用户信息
      this.asyncChanUserInfo();
    },
  },
};
</script>

<style lang="less" scoped>
@import url(../assets/css/global.less);
.login {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;

  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url(../assets/img/login-box-bg.png);
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .close {
      position: absolute;
      right: 60px;
      top: 20px;
    }
    .title {
      display: flex;
      padding-top: 30px;
      justify-content: center;
      align-items: center;
      font-size: 18px;
      color: #ccc;
      li {
        cursor: pointer;
      }

      .active {
        color: #333;
      }
    }
    //登录主体
    .body {
      width: 360px;

      margin: 50px auto 0;
      .form {
        .input-group {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          input {
            flex: 1;
            height: 50px;
            box-sizing: border-box;
            text-indent: 10px;
            &:hover {
              border: 1px solid rgb(157, 213, 240);
            }
          }
          .get-code {
            width: 100px;
            margin-left: 10px;
            padding: 0 10px;
            font-size: 16px;
          }
        }

        .btn {
          height: 50px;
          font-size: 18px;
          font-weight: normal;
          font-stretch: normal;
          line-height: 50px;
          text-align: center;
          letter-spacing: 4px;
          color: #ffffff;
          background-color: @base-color;
          cursor: pointer;
        }
      }
    }
  }
  // 验证码
  /deep/.slide-verify-slider {
    box-sizing: border-box;
  }
  /deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    margin-bottom: 20px;

    canvas {
      position: absolute;
      left: 0;
      top: -140px;
      display: none;
      width: 100%;
      box-sizing: border-box;
    }
    .slide-verify-block {
      width: 85px;
      height: 136px;
    }
    .slide-verify-refresh-icon {
      top: -140px;
      display: none;
    }
    &:hover {
      canvas {
        display: block;
      }
      .slide-verify-refresh-icon {
        display: block;
      }
    }
  }
}
</style>